package net.stogi.common.security.spring;

import net.stogi.common.security.dto.PrincipalData;
import net.stogi.common.security.exception.AuthenticationException;
import net.stogi.common.security.service.SecurityService;

import org.slf4j.Logger;
import org.slf4j.LoggerFactory;
import org.springframework.security.core.Authentication;
import org.springframework.security.core.context.SecurityContextHolder;

public class SpringSecurityServiceImpl implements SecurityService {

	protected final Logger log = LoggerFactory.getLogger(SpringSecurityServiceImpl.class);

	@Override
	public PrincipalData getLoggedUserPrincipalData() throws AuthenticationException {
		Authentication authentication = SecurityContextHolder.getContext().getAuthentication();

		// Is context not null.
		if (authentication != null) {
			Object principal = authentication.getPrincipal();

			// Is principal instance of common principal class.
			if (principal instanceof PrincipalUserDetails) {
				return ((PrincipalUserDetails) principal).getPrincipalData();
			}
			else {
				log.warn("No PrincipalUserDetails instance");
				throw new AuthenticationException("No PrincipalUserDetails instance");
			}
		}
		else {
			log.warn("No user logged in");
			throw new AuthenticationException("No user logged in");
		}
	}
}
